﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Rabbit
{
   public class AmqpUriConnectionFactory : ConnectionFactory
   {
      public readonly string AmqpRe = "^amqp://"
         + "((?<username>[^:]*)[:](?<password>[^@]*)[@])?"
         + "((?<host>[^/:]*)([:](?<port>[^/]*))?)"
         + "(?<virtual_host>/[^/]*)/?"
         + "([?](?<query>[^/]*))?$";

      public string Uri;
      public bool validUri = false;

      public AmqpUriConnectionFactory(string uri)
         : base()
      {
         Uri = uri;

         Match amqpMatch = Regex.Match(uri, AmqpRe);
         validUri = amqpMatch.Success;

         if (!string.IsNullOrEmpty(amqpMatch.Groups["username"].Value))
         {
            UserName = amqpMatch.Groups["username"].Value;
         }
         if (!string.IsNullOrEmpty(amqpMatch.Groups["password"].Value))
         {
            Password = amqpMatch.Groups["password"].Value;
         }
         if (!string.IsNullOrEmpty(amqpMatch.Groups["virtual_host"].Value))
         {
            VirtualHost = amqpMatch.Groups["virtual_host"].Value;
         }
         if (!string.IsNullOrEmpty(amqpMatch.Groups["host"].Value))
         {
            HostName = amqpMatch.Groups["host"].Value;
         }
         if (!string.IsNullOrEmpty(amqpMatch.Groups["port"].Value))
         {
            Port = int.Parse(amqpMatch.Groups["port"].Value);
         }
      }
   }
}
